<template>
  <form class="xtx-form" @submit="onSubmit">
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>
        {{ `Hi，${nickName} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~` }}
      </p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <input
          class="input"
          type="text"
          placeholder="绑定的手机号"
          v-model="mobileField"
        />
      </div>
      <div class="error" v-if="mobileError">{{ mobileError }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <input
          class="input"
          type="text"
          placeholder="短信验证码"
          v-model="codeField"
        />
        <span class="code" @click="getMsgCode">{{
          count === 0 ? "发送验证码" : `剩余${count}秒`
        }}</span>
      </div>
      <div class="error" v-if="codeError">{{ codeError }}</div>
    </div>
    <input type="submit" class="submit" value="立即绑定" />
  </form>
</template>

<script>
import { ref } from "vue";
import { useField, useForm } from "vee-validate";
import { mobile, code } from "@/utils/vee-validate-schema";
import { getBindMobileMsgCode, bindMobileAndQQ } from "@/api/user";
import useCountDown from "@/hooks/useCountDown";
import Message from "@/components/library/Message";
import useLoginAfter from "@/hooks/useLoginAfter";
export default {
  name: "LoginCallbackBindPhone",
  props: {
    openId: {
      type: String,
    },
  },
  setup(props) {
    // 获取qq登录信息
    const { nickName, avatar } = useQQuserInfo();
    const { handleSubmit, getMobileIsValidate, ...test } =
      useBindPhoneValidate();
    const { loginFailed, loginSuccessful } = useLoginAfter();
    const onSubmit = handleSubmit((values) => {
      bindMobileAndQQ({
        unionId: props.openId,
        mobile: values.mobile,
        code: values.code,
      })
        .then(loginSuccessful)
        .catch(loginFailed);
    });
    // 获取倒计时
    const { count, start, isActive } = useCountDown();
    // 发送验证码
    const getMsgCode = async () => {
      const { isValid, mobile } = await getMobileIsValidate();
      if (isValid && !isActive.value) {
        try {
          await getBindMobileMsgCode(mobile);
          Message({ type: "success", text: "验证码发送成功" });
          //     // 开启倒计时
          start(60);
        } catch (error) {
          Message({
            type: "error",
            text: error.response.data.message,
          });
        }
      }
      // getMobileIsValidate()
      //   .then(({ isValid, mobile }) => {
      //     try {
      //
      //     }
      //     // 如果手机号验证通过
      //     if (isValid) return getBindMobileMsgCode(mobile);
      //   })
      //   .then(() => {
      //     Message({ type: "success", text: "验证码发送成功" });
      //     // 开启倒计时
      //     start(60);
      //   })
      //   .catch((error) => {
      //     Message({
      //       type: "error",
      //       text: `验证码发送失败 ${error.response.data.message}`,
      //     });
      //   });
    };
    return {
      nickName,
      avatar,
      onSubmit,
      ...test,
      getMsgCode,
      count,
    };
  },
};
// 获取qq登录信息
function useQQuserInfo() {
  // QQ名称
  const nickName = ref();
  // QQ头像
  const avatar = ref();
  // 当qq登陆成功获取信息
  if (window.QC.Login.check()) {
    // 获取qq登录信息
    window.QC.api("get_user_info").success((response) => {
      console.log(response);
      nickName.value = response.data.nickname;
      avatar.value = response.data.figureurl_1;
    });
  }
  return { nickName, avatar };
}
// 验证手机号和验证码格式
function useBindPhoneValidate() {
  const { handleSubmit } = useForm({
    validationSchema: { mobile, code },
  });
  const {
    value: mobileField,
    errorMessage: mobileError,
    validate,
  } = useField("mobile");
  const { value: codeField, errorMessage: codeError } = useField("code");

  // 单独验证手机号
  const getMobileIsValidate = async () => {
    const { valid } = await validate();
    return { isValid: valid, mobile: mobileField.value };
  };
  return {
    handleSubmit,
    mobileField,
    mobileError,
    codeField,
    codeError,
    getMobileIsValidate,
  };
}
</script>

<style scoped lang="less">
.user-info {
  width: 320px;
  height: 70px;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin: 0 auto 20px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
